<?php
namespace app\beautiful\controller\miniapp\staff\appointment;
use app\BaseController;
use app\beautiful\model\appointment\AppointmentModel;
use app\beautiful\model\appointment\AppointmentSettingModel;
use app\beautiful\model\appointment\TechnicianModel;
use app\beautiful\model\appointment\TechnicianProjectModel;
use app\beautiful\model\appointment\TechnicianSchedulingModel;
use app\beautiful\model\project\ProjectModel;
use app\beautiful\model\setting\SettingSmsModel;
use app\common\logic\SmsLogic;

class TechnicianScheduling extends BaseController{
    protected $technician;
    protected $setting;

    protected function initialize()
    {
        if(null === $setting= AppointmentSettingModel::where([['shop_id','=',$this->request->shopId]])->find()){
            $this->error('您还未设置预约')->send();
            die();
        }
        $this->setting=$setting;
        if(null ===$technician= TechnicianModel::where([
                ['shop_id','=',$this->request->shopId],
                ['status','=',1],
                ['is_delete','=',0],
                ['mobile','=',$this->request->member->mobile]
            ])->find()){
            $this->error('您不是技师')->send();
            die();
        }
        $this->technician=$technician;

        if (!in_array(13, $this->request->staff->add_value_jurisdiction)) {
            $this->error('您没有我的排班的权限')->send();
            die();
        }
    }

    public function getTechnicianSchedulingList()
    {
        $day=$this->request->param('day');
        if(empty($day)) return $this->error('参数错误');
        if(false === strtotime($day.' 00:00:00')) return $this->error('参数错误');
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['technician_id','=',$this->technician->technician_id],
            ['day','=',$day],
            ['is_delete','=',0]
        ];
        $datas=TechnicianSchedulingModel::with(['project'=>function($query){
            $query->field('project_id,abbreviation');
        }])->where($where)->field('scheduling_id,project_id,start_time,end_time')
        ->select()
        ->toArray();
        $return['datas']=$datas;
        $return['week']=$this->setting->week;
        return $this->success($return);
    }

    public function chooseProject()
    {
        $project_ids=TechnicianProjectModel::where([
                ['shop_id','=',$this->request->shopId],
                ['technician_id','=',$this->technician->technician_id],
                ['is_delete','=',0]
            ])->column('project_id') ?? [];

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['project_id','in',$project_ids]
        ];

        $project_model= new ProjectModel();
        $order=['add_time'=>'desc'];
        $field='project_id,abbreviation,market_price,cover_img';
        $datas=$project_model->where($where)->order($order)
            ->field($field)
            ->select()
            ->toArray();
        $return['datas']=$datas;
        return $this->success($return);
    }

    public function addTechnicianScheduling()
    {
        $today=date("Y-m-d",$this->request->time());
        $day=$this->request->param('day');
        $start_time=$this->request->param('start_time');
        $end_time=$this->request->param('end_time');
        $project_id=$this->request->param('project_id/d',0);
        $appointment_num=$this->request->param('appointment_num/d',0);

        if($project_id==0) return $this->error('请选择服务项目');
        if(empty($day)) return $this->error('请选择预约日期');
        if(false === $day_unix=strtotime($day.' 00.00.00')) return $this->error('请选择预约日期');
        if($day<$today) return $this->error('预约日期不能低于今天');
        if(!in_array(date('w',$day_unix),$this->setting->week)) return $this->error('选的日期不能进行排班');
        if(empty($start_time) || empty($end_time)) return $this->error('请选择预约时间');
        if(false === $start_time_unix=strtotime($day.' '.$start_time.':00')) return $this->error('请选择预约开始时间');
        if($start_time_unix<=$this->request->time()) return $this->error('预约开始时间低于当前时间');
        if(false === $end_time_unix=strtotime($day.' '.$end_time.':00')) return $this->error('请选择预约结束时间');
        $interval=$end_time_unix-$start_time_unix;
        if($interval<=0) return $this->error('预约开始时间不能大于结束时间');
        if($interval%1800!=0)return $this->error('预约时间间隔必须是30分钟的整倍');
        if(empty($appointment_num) || $appointment_num<=0) return $this->error('请输入同时段预约人数，且不能小于0');


        if(null === $project = ProjectModel::find($project_id)) return $this->error('项目不存在，请重新选择');
        if($project->shop_id != $this->request->shopId) return $this->error('项目不存在，请重新选择');
        if($project->is_delete != 0) return $this->error('项目不存在，请重新选择');

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['technician_id','=',$this->technician->technician_id],
            ['day','=',$day],
        ];


        if((null !== TechnicianSchedulingModel::where($where)->whereRaw("NOT ((end_time <= '{$start_time}') OR (start_time >= '{$end_time}'))")->find())){
            return $this->error('该时段与别的时间段重叠了,请重新选择');
        }

        $technician_scheduling_model= new TechnicianSchedulingModel();
        $technician_scheduling_model->shop_id=$this->request->shopId;
        $technician_scheduling_model->project_id=$project_id;
        $technician_scheduling_model->technician_id=$this->technician->technician_id;
        $technician_scheduling_model->day=$day;
        $technician_scheduling_model->start_time=$start_time;
        $technician_scheduling_model->end_time=$end_time;
        $technician_scheduling_model->appointment_num=$appointment_num;
        $technician_scheduling_model->save();
        return $this->success('添加成功');
    }

    public function delTechnicianScheduling()
    {
        $scheduling_id=$this->request->param('scheduling_id/d',0);
        if($scheduling_id==0) return $this->error('排班不存在');

        if(null === $technician_scheduling = TechnicianSchedulingModel::find($scheduling_id))  return $this->error('排班不存在');
        if($technician_scheduling->shop_id != $this->request->shopId)  return $this->error('排班不存在');
        if($technician_scheduling->technician_id != $this->technician->technician_id)  return $this->error('排班不存在');
        if($technician_scheduling->is_delete != 0)  return $this->error('排班不存在');

        $technician_scheduling->is_delete=1;
        $technician_scheduling->save();

        $appointment=AppointmentModel::where([
            ['shop_id','=',$this->request->shopId],
            ['scheduling_id','=',$scheduling_id],
            ['status','in',[1,4]]
        ])->select()->toArray();
        if(!empty($appointment)){
            $mobiles=[];
            foreach ($appointment as $k => $v){
                $appointment[$k]['status']=-1;
                $appointment[$k]['cancel_time']=$this->request->time();
                $appointment[$k]['reason']='技师排班删除导致的取消';
                $appointment[$k]['operate_type']=1;
                $appointment[$k]['operate_id']=$this->request->staffId;
                $appointment[$k]['operate_name']=$this->request->staff->name;
                $appointment[$k]['operate_mobile']=$this->request->staff->mobile;
                $mobiles[]=$v['member_mobile'];
            }
            $appointment_model=new AppointmentModel();
            $appointment_model->saveAll($appointment);

            //发送短信给用户
            try{
                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
                if(null !== $sms_setting){
                    if($sms_setting->cancel_appointment==1){
                        $sms_logic= new SmsLogic();
                        $params=[
                            'xm'=>$appointment[0]['project_name'],
                        ];
                        $sms_logic->send($this->request->shopId,$mobiles,$params,'cancelAppointment');
                    }
                }
            }catch (\Exception $e){

            }
        }

        return $this->success('删除成功');
    }


}
